import { Service } from 'egg';
import { Anexcuse } from '../model/Anexcuse';

import { User } from '../model/User';

export default class AccusationService extends Service {
    /**
     * 查询全部举报记录
     * @param offset
     */
    public async searchAccusationAll(param: any) {
        const limit = Number(param.size);
        const offset = (Number(param.page) - 1) * limit;
        let actuleParam: any = {};
        let queryStr = `select a.accusation_id, u1.user_id as report_user_id,u1.user_nickname as report_user_nickname,u1.user_phone as report_user_phone,u1.user_sex as report_user_sex,s1.school_name as report_school_name,u.user_nickname,u.user_phone,a.accusation_reason,`
            + `a.accusation_type,a.accusation_picture,a.accusation_status,a.created_at from t_accusation a left join t_user u on a.user_id=u.user_id left join t_school s on`
            + ` u.user_school_id=s.school_id and s.school_status='1' left join t_user u1 on a.report_user_id=u1.user_id and u1.is_delete='1' inner join t_school s1 on`
            + ` u1.user_school_id=s1.school_id and s1.school_status='1' where a.is_delete='1'`;
        if (param.accusation_people_phone) {
            queryStr += ` and u1.user_phone like :accusation_people_phone`;
            actuleParam.accusation_people_phone = '%' + param.accusation_people_phone + '%';
        }
        if (param.user_sex) {
            queryStr += ` and u1.user_sex = :user_sex`;
            actuleParam.user_sex = param.user_sex;
        }
        if (param.user_school) {
            queryStr += ` and u1.user_school_id = :user_school_id`;
            actuleParam.user_school_id = param.user_school;
        }
        const queryAllStr = queryStr + ` order by created_at DESC`;
        queryStr += ` order by created_at DESC limit ${offset},${limit}`;
        const user = await this.ctx.model.query(
            queryStr,
            {
                type: this.ctx.model.QueryTypes.SELECT,
                replacements: actuleParam
            },
        );
        const count = await this.ctx.model.query(
            queryAllStr,
            {
                type: this.ctx.model.QueryTypes.SELECT,
                replacements: actuleParam
            },
        );
        if (user.length <= 0) {
            throw new Error(JSON.stringify({ code: '2', msg: '查询无记录' }));
        }
        const result = { count: count.length, userInfo: user };
        return result;
    }

    /**
     * 获取系统默认禁言时间
     */
    public async getSystemExcuseTime() {
        const setting = await this.service.settingService.searchAllSetting();
        let excuse_time = '';
        for (let i = 0; i < setting.length; i++) {
            if (setting[i]['setting_key'] === "userExcuseTime") {
                excuse_time = setting[i]['setting_value'];
            }
        }
        const result = { excuse_time: excuse_time };
        return result;
    }

    /**
     * 操作举报状态
     * @param param
     */
    public async editAccusationStatus(param: any) {
        let type = Number(param.type);
        let accusation_status = Number(param.accusation_status);
        let status: string = '';
        if (type === 1) {
            status = '1';
        } else if (type === 2) {
            status = '3';
        } else if (type === 3) {
            status = '4';
        } else if (type === 4) {
            status = '5';
        } else if (type === 5) {
            status = '1'
        } else {
            throw new Error(JSON.stringify({ code: 2, msg: '无法识别的操作类型' }));
        }
        const tran = await this.ctx.model.transaction();
        const Op = this.ctx.model.Op;
        try {
            const user: any = await this.ctx.model.User.findOne<User>({ attributes: ['user_status'], where: { user_id: param.report_user_id }, transaction: tran });
            const current_user_status = Number(user['user_status']);
            if (type === 2) {
                await this.ctx.model.Accusation.update({ accusation_status: status }, { where: { accusation_id: param.accusation_id }, transaction: tran });
            }
            if (type === 1 && accusation_status === 4) {
                await this.ctx.model.Accusation.update({ accusation_status: status }, { where: { accusation_status, report_user_id: param.report_user_id }, transaction: tran });
                await this.ctx.model.Anexcuse.update({ is_delete: '2', anexcuse_time: 0 }, { where: { user_id: param.report_user_id }, transaction: tran });
                await this.ctx.model.User.update({ user_status: '3' }, { where: { user_id: param.report_user_id }, transaction: tran });
            }
            if (type === 1 && accusation_status === 5) {
                await this.ctx.model.Accusation.update({ accusation_status: status }, { where: { accusation_status, report_user_id: param.report_user_id }, transaction: tran });
                await this.ctx.model.Anexcuse.update({ is_delete: '2', anexcuse_time: 0 }, { where: { user_id: param.report_user_id }, transaction: tran });
                await this.ctx.model.User.update({ user_status: '3' }, { where: { user_id: param.report_user_id }, transaction: tran });
            }
            if (type === 4) {
                if (current_user_status === 1) {
                    throw new Error(JSON.stringify({ code: 2, msg: '该用户已被封号' }));
                }
                await this.ctx.model.Accusation.update({ accusation_status: status }, { where: { accusation_status: { [Op.ne]: '1' }, report_user_id: param.report_user_id }, transaction: tran });
                await this.ctx.model.User.update({ user_status: '1' }, { where: { user_id: param.report_user_id }, transaction: tran });
                const resultAnexcuse = await this.ctx.model.Anexcuse.findOne<Anexcuse>({ attributes: ['anexcuse_id'], where: { user_id: param.report_user_id, is_delete: '1' }, transaction: tran });
                if (resultAnexcuse) {
                    await this.ctx.model.Anexcuse.update({ is_delete: '2', anexcuse_time: 0 }, { where: { anexcuse_id: resultAnexcuse['anexcuse_id'] }, transaction: tran });
                }
            }
            if (type === 3) {
                if (current_user_status === 1) {
                    throw new Error(JSON.stringify({ code: 2, msg: '该用户已被封号' }));
                }
                await this.ctx.model.Accusation.update({ accusation_status: status }, { where: { accusation_status: { [Op.ne]: '1' }, report_user_id: param.report_user_id }, transaction: tran });
                await this.ctx.model.User.update({ user_status: '2' }, { where: { user_id: param.report_user_id }, transaction: tran });
                let anexcuse_time = Number(param.anexcuse_time);
                const resultAnexcuse = await this.ctx.model.Anexcuse.findOne<Anexcuse>({ attributes: ['anexcuse_id', 'anexcuse_time', 'is_delete'], where: { user_id: param.report_user_id }, transaction: tran });
                if (!resultAnexcuse) {
                    const submitData: any = {};
                    submitData.anexcuse_id = this.ctx.helper.genUUID();
                    submitData.user_id = param.report_user_id;
                    submitData.anexcuse_time = anexcuse_time;
                    submitData.is_delete = '1';
                    await this.ctx.model.Anexcuse.create(submitData, { transaction: tran });
                } else {
                    const is_delete = resultAnexcuse['is_delete'];
                    if (is_delete == 1) {
                        const anexcuse_time = resultAnexcuse['anexcuse_time'] + Number(param.anexcuse_time);
                        await this.ctx.model.Anexcuse.update({ anexcuse_time }, { where: { anexcuse_id: resultAnexcuse['anexcuse_id'] }, transaction: tran });
                    } else if (is_delete == 2) {
                        const anexcuse_time = Number(param.anexcuse_time);
                        await this.ctx.model.Anexcuse.update({ anexcuse_time, is_delete: '1' }, { where: { anexcuse_id: resultAnexcuse['anexcuse_id'] }, transaction: tran });
                    }
                }
            }
            if (type === 5) {
                console.log('删除解忧');
            }
            await tran.commit();
        } catch (e) {
            await tran.rollback();
            this.logger.error(e);
            const errorMsg: any = JSON.parse(e.message);
            throw new Error(JSON.stringify({ code: 2, msg: errorMsg.msg }));
        }
    }

}
